package ch.mueller.android.sensorexample.sensorpages.accelerometer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import ch.mueller.android.sensorexample.R;

public class Accelerometer extends Fragment implements SensorEventListener {

    private static final String FILENAME = "acceleratordump.txt";
    private static final String FOLDERNAME = "SenSORsation";

    private File dir;
    private File file;

    FileOutputStream outputStream;
    OutputStreamWriter streamWriter;

    private SensorManager sensorManager;
    private TextView xValue, yValue, zValue;
    private Button startButton, stopButton, deleteButton;
    private boolean recording = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.accelerometer, container, false);
        xValue = (TextView) rootView.findViewById(R.id.tx_x_axis_value);
        yValue = (TextView) rootView.findViewById(R.id.tx_y_axis_value);
        zValue = (TextView) rootView.findViewById(R.id.tx_z_axis_value);
        startButton = (Button) rootView.findViewById(R.id.bu_accelerometer_startrecording);
        stopButton = (Button) rootView.findViewById(R.id.bu_accelerometer_stoprecording);
        deleteButton = (Button) rootView.findViewById(R.id.bu_accelerometer_deleterecord);
        sensorManager = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
        if (sensorList.size() > 0) {
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_UI);
        }

        startButton.setOnClickListener(new ButtonListener());
        stopButton.setOnClickListener(new ButtonListener());
        stopButton.setEnabled(false);
        deleteButton.setOnClickListener(new ButtonListener());
        deleteButton.setEnabled(false);

        try {
            dir = new File(Environment.getExternalStorageDirectory(), FOLDERNAME);
            if (!dir.exists()) {
                dir.mkdir();
            }

            file = new File(dir, FILENAME);

            if (!file.exists()) {
                file.createNewFile();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            String xval = " " + event.values[0];
            String yval = " " + event.values[1];
            String zval = " " + event.values[2];
            xValue.setText(xval);
            yValue.setText(yval);
            zValue.setText(zval);

            if (recording) {
                write2File(new String[] { xval, yval, zval });
            }

        }
    }

    private void write2File(String[] values) {

        try {

            String string = values[0] + ";" + values[1] + ";" + values[2];

            streamWriter.append(string);
            streamWriter.append("\n");

        } catch (IOException e) {
            Toast.makeText(getActivity(), "ERROR: " + e, Toast.LENGTH_LONG).show();
            recording = false;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            try {
                streamWriter.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();

        }
    }

    public void buttonClicked(View view) {
        switch (view.getId()) {
        case R.id.bu_accelerometer_startrecording:
            Toast.makeText(getActivity(), "Start", Toast.LENGTH_SHORT).show();
            try {

                outputStream = new FileOutputStream(file);
                streamWriter = new OutputStreamWriter(outputStream);
                recording = true;
            } catch (Exception e) {
                Toast.makeText(getActivity(), "WTF", Toast.LENGTH_SHORT).show();
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            deleteButton.setEnabled(false);
            break;
        case R.id.bu_accelerometer_stoprecording:
            Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            deleteButton.setEnabled(true);
            try {
                streamWriter.close();
            } catch (Exception e) {
                Toast.makeText(getActivity(), "WTF", Toast.LENGTH_SHORT).show();
            }
            recording = false;
            break;
        case R.id.bu_accelerometer_deleterecord:
            try {
                File file = new File(dir, FILENAME);
                if (file.delete()) {
                    Toast.makeText(getActivity(), "Delete", Toast.LENGTH_SHORT).show();
                }
                deleteButton.setEnabled(false);
            } catch (Exception e) {
                Toast.makeText(getActivity(), "WTF", Toast.LENGTH_SHORT).show();
            }

            break;
        default:
            break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private class ButtonListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            buttonClicked(v);

        }

    }

}